package test.study.mybatis.client;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.sql.Connection;

public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;
    private static SqlSession sqlSession;
    private static Configuration config;

    static {
        try {
            InputStream is = Resources.getResourceAsStream("test-mybatis-cfg.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            sqlSession = sqlSessionFactory.openSession();
            config = sqlSession.getConfiguration();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static Configuration getConfig() {
        return config;
    }

    public static SqlSession getSqlSession() {
        return sqlSession;
    }

    public static Connection getConnection() {
        return getSqlSession().getConnection();
    }

    public static SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }

}
